package com.lingyun.financialmanagement.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.generator.IFill;
import com.lingyun.financialmanagement.service.LoginService;
import com.lingyun.financialmanagement.vo.ErrorCode;
import com.lingyun.financialmanagement.vo.Result;
import com.lingyun.financialmanagement.vo.UserRole;
import com.mysql.cj.log.Log;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class Interceptor implements HandlerInterceptor {
    // 设置三个权限
    private static final List<String> ADMIN_ROLE = Arrays.asList("/admin/**");
    private static final List<String> USERS_ROLE = Arrays.asList("/user/**");
    private static final List<String> ACCOUNTANT = Arrays.asList("/accountant/**");

    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${redis.token.tokenAccountPrefix}")
    private String tokenAccountPrefix;

    @Value("${redis.token.tokenRolePrefix}")
    private String tokenRolePrefix;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json; charset=utf-8");

        String token = request.getHeader("token");
//
//        // 跨域请求如果为此则拒绝访问
//        if ("OPTIONS".equals(request.getMethod())) {
//            response.setStatus(HttpServletResponse.SC_OK);
//            return false;
//        }
//
//        // token是否为空
//        if (token == null){
//            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
//            response.getWriter().print(JSON.toJSONString(result));
//            log.error("请求token为空");
//            return false;
//        }
//
//        // token验证
//        Boolean checkToken = loginService.checkToken(token);
//        if (!checkToken){
//            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
//            response.getWriter().print(JSON.toJSONString(result));
//            log.error("token验证失败");
//            return false;
//        }
//
//        // 权限认证
//        String requestURI = request.getRequestURI();
//        boolean checkRole = checkRole(token, requestURI);
//        if (!checkRole){
//            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
//            response.getWriter().print(JSON.toJSONString(result));
//            log.error("token权限错误");
//            return false;
//        }
        return true;
    }

    private boolean checkRole(String token, String requestURI){
        String account = redisTemplate.opsForValue().get(tokenAccountPrefix + token);
        if (account == null || account.isEmpty()){
            return false;
        }
        String role = redisTemplate.opsForValue().get(tokenRolePrefix + account);
        if (role == null || role.isEmpty()){
            return false;
        }

        if (UserRole.USER.getRole().equals(role)){
            return true;
        } else if (UserRole.ADMIN.getRole().equals(role)) {
            return true;
        } else if (UserRole.ACCOUNTANT.getRole().equals(role)) {
            return true;
        }
        return false;
    }
}
